// JavaScript Document

var image_manager = {

	startPos: 0,
	page: 0,
	limit: 30,
	image_category: 'cms',
	
    /**
     * Initialises the image manager object by attaching the necessary event handlers
     * and loading the list of images to display
     */
    init: function(params) {
        
        // attach a handler to the uploadFile field if it exists
        pageManager.addEvent('uploadFile', 'change', function(evt) {
			
			// for HTML5 compliant browsers we can check file size before upload
			if( evt.target && evt.target.files ) {
				var size = evt.target.files[0].size; 
				var type = evt.target.files[0].type; 
				var max_size = $p("#maxlimit").val();
	 
				if (size > max_size) {
					alert("The File You Are Trying To Upload Is Greater Than The Max Limit of " + max_size + " Bytes Permitted. "
						+ "Please Resize Image Before Attempting Upload.");
				  
					$p(this).val("");
					return false;
				}
			}
            
            var dstFolder = document.getElementById("destFolder").value;
            var file_path = document.getElementById("uploadFile").value;
			
			// calculate the data time to be used as the destination file name
			var now = new Date();
            var dateStr = now.getFullYear() + "" + (now.getMonth() + 1) + "" + now.getDate() + "_" + now.getHours() + "" + now.getMinutes() + "" + now.getSeconds();
			document.getElementById('destFileName').value = "img" + dateStr;
			
			// generate the destination file name to used for the picture field
            file_utils.generateDestinationFileName('Picture', dstFolder, file_path, 'img');
        });

        // attach a handler to the UseSection field if it exists
        pageManager.addEvent('UseSection', 'change', function() {
            
            // update the folder information based on the image category chosen
            image_manager.processSelection(this);

            // incase a file selection has already been made, we will need to update
            // the generated destination file information
            if( pageManager.$("#uploadFile").value != "" ) {
                 // generate the destination file name
                var dstFolder = document.getElementById("destFolder").value;
                var file_path = document.getElementById("uploadFile").value;
                file_utils.generateDestinationFileName('Picture', dstFolder, file_path, 'img');
            }
        });
		
		// add event listener for delete_link
		pageManager.addEvent('upload_link', 'click', function() {
			window.location.href = '?upload&cat=' + image_manager.getImageCategory();
		});
		
		// add event listener for delete_link
		pageManager.addEvent('delete_link', 'click', function() {
			image_manager.deleteImages();
		});
		
		// add event listner for prev_link
		pageManager.addEvent('prev_link', 'click', function() {
			image_manager.showPrevPage();
		});
		
		// add event listner for prev_link
		pageManager.addEvent('next_link', 'click', function() {
			image_manager.showNextPage();
		});
		
		// add event listner for limit_form
		pageManager.addEvent('limit_form', 'submit', function() {
			image_manager.setLimit( pageManager.$("#limit").value );
		});
		
		// add event listner for limit_form
		pageManager.addEvent('limit', 'blur', function() {
			image_manager.limit = this.value;
		});

        // process the currently selected image category
        image_manager.processSelection( document.getElementById("UseSection") );

        if( params.use_section ) {
            image_manager.showImages(params.use_section);
        }
    },
	
	/**
	 * Returns the current image category code
	 */
	getImageCategory: function() {
		return image_manager.image_category;
	},

    /**
     * Loads and displays the images in the specified category
     */
    showImages: function(cat, index) {
		
        if( index != null ) {
            tabs.selectTab(index);
        }
		
        image_manager.image_category = cat;
        var query = "action=load_images&cat=" + cat + "&startPos=" + image_manager.startPos + "&limit=" + image_manager.limit;
		
        pageManager.post('ajax_pages/img_list_loader.php', query, function(data) {
			$p("#tab_content").html(data);
		});
    },
	
	/**
	 * Shows the next page of images based on the limit and startpos
	 */
	showNextPage: function() {
		image_manager.startPos = ++image_manager.page * image_manager.limit;
		
		image_manager.showImages( image_manager.getImageCategory() );
	},
	
	/**
	 * Shows the previous page of images based on the limit and startpos
	 */
	showPrevPage: function() {
		image_manager.startPos = --image_manager.page * image_manager.limit;
		
		if( image_manager.page <= 0 ) {
			image_manager.startPos = 0;
			image_manager.page = 0;
		}
		
		image_manager.showImages( image_manager.getImageCategory() );
	},
	
	/**
	 * Sets the limit for the number of images that can be displayed in the image list display
	 *
	 * @param val the new value of the limit
	 */
	setLimit: function(val) {
		image_manager.limit = val;
		image_manager.showImages( image_manager.getImageCategory() );
	},

    /**
     * Processes the selected image category and updates the destFolder and thumbFolder
     * fields accordingly
     **/
    processSelection: function(selector) {
        if(selector == null) {
            return;
        }

        var selValue = selector.options[selector.selectedIndex].value;

        var obj = document.getElementById(selValue + "_row");
        if( obj != null ) {
        //obj.style.display = "block";
        }

        if(selValue == "news") {
            document.getElementById("destFolder").value = "../assets/images/news/pics/";
            document.getElementById("thumbFolder").value = "../assets/images/news/thumbs/";
        } else if(selValue == "sidebar") {
            document.getElementById("destFolder").value = "../assets/images/sidebar/";
            document.getElementById("thumbFolder").value = "../assets/images/sidebar/";
        } else {
            document.getElementById("destFolder").value = "../assets/images/content/pics/";
            document.getElementById("thumbFolder").value = "../assets/images/content/thumbs/";
        }
    },
	
	/**
	 * Deletes all the selected images in the image manager display
	 */
	deleteImages: function() {
		/**
		 * IE8 does not support the :checked psuedo class hence we have to resort to
		 * the simple selector and in order to be cross platform
		 */
		var selectedImages = pageManager.all("#delForm input[type=checkbox]");
		//selectedImages = pageManager.all("#delForm input[type=checkbox]:checked");
		
		if( selectedImages != null ) {
			if( selectedImages.length == 0 ) {
				alert("Please Select Images To Delete Before Using This Option");	
				return;
				
			} else if( !confirm('Delete Information and Data For Selected Images?') ) {
				return;
				
			}
			
			// create an array with all the IDs of the selected images
			var img_ids = new Array();
			for(var i = 0, j = 0; i < selectedImages.length; i++) {
				
				// check for selected items and for items with a value != 'on'
				// in case the check all box is used
				if( selectedImages[i].checked && selectedImages[i].value != 'on' ) {
					img_ids[j++] = selectedImages[i].value;
				}
			}
			
			var query = "action=delete_images&img_ids=" + img_ids;
			pageManager.post('ajax_pages/img_list_loader.php', query, function(data) {
				$p('#tab_content').html(data);
				
				for(var i = 0, j = 0; i < selectedImages.length; i++) {
					// check for selected items and for items with a value != 'on'
				    // in case the check all box is used
					if( selectedImages[i].checked && selectedImages[i].value != 'on' ) {
						var parent = pageManager.findFirstParentWithClass(selectedImages[i], 'img_box');
						if( parent != null ) {
							parent.parentNode.removeChild(parent);
						}
					}
				}																		 
			});
		}
	},
	
	/**
	 * Deletes a specific image from the database and removes the display element after
	 *
	 * @param el the element that triggers the delete action
	 * @param img_id the id of the image in the database
	 */
	deleteImage: function(el, img_id) {
		if( !confirm('Delete Selected Image From Database?') ) {
			return false;
		}
		
		// create a query that uses the  general delete_images action and in this 
		// case just pass a single image to be deleted. 
		var query = "action=delete_images&img_ids=" + img_id;
		
		// fire the ajax event
		pageManager.post('ajax_pages/img_list_loader.php', query, null, function() {
			var parentEl = pageManager.findFirstParentWithClass(el, 'img_box');
			
			if( parentEl != null ) {
				parentEl.parentNode.removeChild( parentEl );	
			}
		});

        return true;
	}
};